﻿const Rule = require('./rule');
const logger = require('../logs/logger');
const url = require('url');
const qs = require('querystring');

_args = {};

class CommentRule extends Rule {
    constructor(args) { super(args); _args = args; }

    get name() { return 'comment rule'; }

    get enable() { return true; }

    isMatch(req, resp) {
        return req.url.indexOf('mp.weixin.qq.com/mp/appmsg_comment?action=getcomment') > -1;
    }

    execute(req, resp) {
        var q = qs.parse(url.parse(req.url).query);
        var comments = JSON.parse(resp.response.body).elected_comment;

        try{
            var cmts = comments.map((v, i, s) => {
                return {
                    id: v.id,
                    biz: q.__biz instanceof Array ? q.__biz[0] : q.__biz,
                    mid: q.appmsgid instanceof Array ? q.appmsgid[0] : q.appmsgid,
                    idx: q.idx instanceof Array ? q.idx[0] : q.idx,
                    isTop: v.is_top,
                    speaker: v.nick_name,
                    avatar: v.logo_url,
                    content: v.content,
                    creation: v.create_time * 1000,
                    likes: v.like_num,
                    replies: v.reply.reply_list.map((r, ii, ss) => {
                        return {
                            uin: r.uin,
                            content: r.content,
                            creation: r.create_time * 1000,
                            toUin: r.to_uin,
                        };
                    })
                };
            });
    
            cmts.forEach((v,i,s) => _args.mq.send('cmt', JSON.stringify(v)));
        } catch(e) {
            logger.debug(`get comments error -> ${JSON.stringify(e)}`);
        }
    }
}

module.exports = CommentRule;